package cn.softeem.tushu.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

//用注解代替web.xml中的配置内容
@WebFilter(filterName = "EncodiongFilter",urlPatterns = "/web/*",
        initParams = {@WebInitParam(name="encoding",value = "utf-8")})
public class EncodiongFilter implements Filter {
    private String encoding;
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        String method = request.getMethod();
        if(method.equalsIgnoreCase("post")){
            req.setCharacterEncoding(encoding);
        }else if(method.equalsIgnoreCase("get")){
            //用getRequest替换当前的请求对象
            /*if(!(req instanceof GetRequest)){
                request =  new GetRequest(request, encoding);
            }*/
        }
        chain.doFilter(request, resp);
    }

    public void init(FilterConfig config) throws ServletException {
        encoding = config.getInitParameter("encoding");
    }
}
